<template>
  <el-row>
    <el-col v-for="item in amDirectoryList" :key="item.id">
      <AmDirectoryUploaderRow :item-data="item" :collapsedIds="collapsedIds"
                              v-model="formTemp.fileDirectoryMap[`${item.id}`]"
                              @toggleExpand="handleRowExpand"/>
    </el-col>
  </el-row>
</template>

<script>
import { listDirectory } from "@/api/am/directory";
import AmFilesUploader from "../../../components/AmComp/AmFilesUploader.vue";
import AmDirectoryUploaderRow from "./AmDirectoryUploaderRow.vue";
import {isEmpty, isUndefined} from "lodash";
import {mapGetters, mapState} from "vuex";
import {getDirIdsByRoleId} from "../../../api/am/directory";

function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push({...d, path: [d[config.id]]});
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null && childrenListMap[o[config.id]] !== undefined) {
      o[config.childrenList] = childrenListMap[o[config.id]].map(item => ({
        ...item,
        path: [...o.path, item[config.id]]
      }));
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
    if(o[config.childrenList]) {
      o[config.childrenList] = o[config.childrenList].sort((a, b) => {
        // console.log(a, b);
        return a.sort - b.sort
      })
    }
  }
  return tree;
}

export default {
  name: "AmDirectoryUploader",
  components: {AmDirectoryUploaderRow, AmFilesUploader},
  data() {
    return {
      formTemp: {
        fileDirectoryMap: {}
      },
      // 文件夹表格数据
      amDirectoryList: [],
      collapsedIds: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 999,
      },
    }
  },
  computed: {
    ...mapState({

    }),
  },
  methods: {
    handleRowExpand(item) {
      const { id } = item;
      if(this.collapsedIds.includes(id)) {
        this.collapsedIds = this.collapsedIds.filter(item => item !== id)
      } else {
        this.collapsedIds.push(id);
      }
    },
    /** 查询文件夹列表 */
    getList(dirIds, fileVOS) {
      this.loading = true;
      listDirectory(this.queryParams).then(response => {
        const treeData = handleTree(response.rows.filter(item => dirIds.includes(item.id)));
        this.amDirectoryList = this.treeToList(treeData);
        this.loading = false;
        this.amDirectoryList.forEach(item => {
          this.formTemp.fileDirectoryMap[`${item.id}`] = []
        })
        if(!isEmpty(fileVOS)) {
          fileVOS.forEach(file => {
            if (isUndefined(this.formTemp.fileDirectoryMap[file.dirId])) {
              this.formTemp.fileDirectoryMap[file.dirId] = [file]
            } else {
              this.formTemp.fileDirectoryMap[file.dirId].push(file)
            }
          })
        }
      });
    },
    treeToList(treeList) {
      function handleTreeList(treeList, list) { //处理数组
        if (!treeList || !treeList.length) {
          return
        }
        for (let i = 0; i < treeList.length; i++) {
          let currentRow = treeList[i];
          let newRow = JSON.parse(JSON.stringify(currentRow));
          newRow.children = undefined;
          list.push(newRow);
          handleTreeList(currentRow.children, list)
        }
      }

      let list = [];
      handleTreeList(treeList, list);
      return list
    },
    getFiles() {
      const fileVOS = []
      Object.keys(this.formTemp.fileDirectoryMap).forEach(key => {
        const currFiles = this.formTemp.fileDirectoryMap[`${key}`];
        if(!isEmpty(currFiles)) {
          const currFilesWithDirId = currFiles.map(file => ({
            // ...file,
            fileId: file.fileId || null,
            dirId: key,
            fileName: file.fileName,
            url: file.url,
          }))
          fileVOS.push(...currFilesWithDirId)
        }
      })
      return fileVOS;
    },
    recoveryFiles(fileVOS = []) {
      const roleIds = this.$store.getters.roleInfos.map(role => role.roleId);
      Promise.all(roleIds.map(id => getDirIdsByRoleId(id))).then(resArr => {
        const dirIdArr = []
        resArr.forEach(res => {
          dirIdArr.push(...res.data)
        })
        const dirIds = Array.from(new Set(dirIdArr))
        this.getList(dirIds, fileVOS)
      })
    }
  },
  mounted() {
    // console.log(this.$store.getters.roleInfos);
    // this.recoveryFiles()

    // this.getList()
  }
}
</script>

<style scoped lang="scss">
.upload-file-uploader {
  display: inline-block;
  margin: 0 16px;
}
.tree-node-heading{
  display: flex;
  .icon-expand{
    padding-right: 10px;
  }
}
</style>
